import React, { PureComponent, lazy, Suspense } from 'react'
import { Route, Switch } from 'react-router-dom'
import config from '@/router/config'
import MenuBar from '@/components/MenuBar'
import Loading from '@/components/Loading'
import css from './index.module.scss'
const Index = lazy(() => import('@/views/Index'))
const Channel = lazy(() => import('@/views/Channel'))
export default class Main extends PureComponent {
    constructor(props) {
        super(props)
        this.state = this.initState()
    }

    initState = () => {
        let currentTab = 0
        const { match: { params } } = this.props
        if (params) {
            const { id } = params
            if (id) {
                currentTab = config.findIndex(item => item.tid === id - 0 && !item.hide)
                currentTab = currentTab < 0 ? 0 : currentTab
            }           
        }

        return {
            tabs: config.filter(item => !item.hide),
            currentTab
        }
    }

    handleTab = (tab, index) => {
        const { tid, route } = tab
        const path = tid === 0 ? route : `/channel/${tid}`
        this.setState({
            currentTab: index 
        })
        this.props.history.push(path)        
    }

    componentDidUpdate() {
        if (this.props.match.url === '/') {
            this.setState({
                currentTab: 0
            })
        }
    }
    
    render() {
        const { currentTab, tabs } = this.state        
        return (
            <>                                         
                <div className={css['mb-sticky']}>                    
                    <MenuBar tabs={tabs} currentTab={currentTab} onTabClick={this.handleTab} />
                </div>                           
                <Suspense fallback={<Loading/>}>
                    <Switch>            
                        <Route path="/channel/:id/:childId?" component={Channel} /> 
                        <Route component={Index} />            
                    </Switch>
                </Suspense>
            </>
        )
    }
}
